// 教师姓名匹配正则
const teacherReg = /[0-9]*\|*(.+)/;
// 时间信息匹配正则
const timeReg = /\{第(\d+)-(\d+)周\|?(\d+)节\/([单|双]?)周\}/;
// 节时间
const sectionTimes = [{
  "section": 1,
  "startTime": "08:00",
  "endTime": "08:45"
}, {
  "section": 2,
  "startTime": "08:55",
  "endTime": "09:40"
}, {
  "section": 3,
  "startTime": "10:00",
  "endTime": "10:45"
}, {
  "section": 4,
  "startTime": "10:55",
  "endTime": "11:40"
}, {
  "section": 5,
  "startTime": "13:00",
  "endTime": "13:45"
}, {
  "section": 6,
  "startTime": "14:00",
  "endTime": "14:45"
}, {
  "section": 7,
  "startTime": "14:55",
  "endTime": "15:40"
}, {
  "section": 8,
  "startTime": "15:50",
  "endTime": "16:35"
}, {
  "section": 9,
  "startTime": "16:45",
  "endTime": "17:30"
}, {
  "section": 10,
  "startTime": "19:00",
  "endTime": "19:45"
}, {
  "section": 11,
  "startTime": "19:55",
  "endTime": "20:40"
}, {
  "section": 12,
  "startTime": "20:55",
  "endTime": "21:35"
}]

function scheduleHtmlParser(html) {
  let result = [];
  const valid_index = [2, 4, 6, 7, 9, 11];
  $('#Table1 tr').each((idx, ele) => {
    if (valid_index.indexOf(idx) >= 0) {
      let tds = $(ele).find('td');
      tds = tds.length === 9 ? tds.slice(2) : tds.slice(1);
      $(tds).each((week, course) => {
        let text = $(course).text();
        if (text !== '&nbsp;') {
          // 数据行
          let lines = unescape(String($(course).html())
            .replace('\n+', '').replace(/(<\/?br\/?>)+/g, '\n')
            .replace(/&#x/g, '%u')
            .replace(/;/g, '')).split('\n');

          const day = week + 1;
          const sections = [];
          const name = lines[0];
          const position = lines[3];
          const teacher = teacherReg.exec(lines[2])[1];
          const weeks = [];

          const match = timeReg.exec(lines[1]);
          const sectionCount = parseInt(match[3]);  // 课程节数
          for (let i = (idx - 1); i < idx + sectionCount - 1; i++) {
            sections.push({'section': i});
          }

          const state = match[4];  // 单双周标记
          for (let i = parseInt(match[1]); i < parseInt(match[2]) + 1; i++) {
            if (state === '单' && (i % 2 !== 0)) {
              weeks.push(i);
            } else if (state === '双' && i % 2 === 0) {
              weeks.push(i);
            } else if (state === '') {
              weeks.push(i);
            }
          }

          result.push({
            "name": name,
            "position": position,
            "teacher": teacher,
            "weeks": weeks,
            "day": day,
            "sections": sections
          });
        }
      });
    }
  });

  return {'courseInfos': result, 'sectionTimes': sectionTimes};
}